/**
 * Created by zhouli on 18/2/8
 * Email li.zhou@huilianyi.com
 */
import React from 'react';
import {connect} from 'react-redux';
import {Button, Form, Input, Select, Switch, Icon,message} from 'antd';
import 'styles/enterprise-manage/org-structure/org-component/org-new-dep.scss';
import OrgService from 'containers/enterprise-manage/org-structure/org-structure.service';
import {LanguageInput} from 'components/index';
import {deepFullCopy, messages, trim} from "share/common";
import Chooser from 'components/chooser';
const FormItem = Form.Item;
const Option = Select.Option;
//两种种类型
//创建子部门
//创建平级部门
class OrgNewDep extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      fKey: 0,
      c_type: "",//C_CHILD 与 C_DEP 代表创建子部门与平级部门
      dep: {
        i18n: {
          name: []
        }
      }
    };
  }

  componentWillReceiveProps(nextprops) {
    let params = nextprops.params;
    this.setDepByprops(params);
  }

  componentDidMount() {
    let params = this.props.params;
    this.setDepByprops(params)

  }

  setDepByprops = (params) => {
    let dep = this.state.dep;
    if (params) {
      //控制选择公司的规则
      dep.isEnableDepCompany = params.isEnableDepCompany;
      if (params.c_type === "C_CHILD") {
        //创建子部门
        dep.parentName = params.name;
        dep.parentDepartmentOID = params.departmentOID;
        dep.parentId = params.id;
        dep.treeNode = params.treeNode;
        //创建子部门默认带入父级部门关联的公司(开启的时候才有)
        if(dep.isEnableDepCompany === "OPEN"){
          dep.companyName =  params.companyName;
          dep.companyOID =  params.companyOID;
        }
        this.setState({c_type: "C_CHILD"})
      } else if (params.c_type === "C_DEP") {
        //创建平级部门
        if (params.parentDepartmentOID || params.parentId) {
          dep.parentName = params.path.split("|")[0];
          //创建平级部门的时候 parentDepartmentOID 不能少
          dep.parentDepartmentOID = params.parentDepartmentOID;
          dep.parentId = params.parentId;
        }else {
          dep.parentName = messages('enterprise-manage.key117'/*已是顶级部门*/);
          dep.parentDepartmentOID = null;
          dep.parentId = null;
        }
        dep.treeNode = params.treeNode;
        this.setState({c_type: "C_DEP"})
      }
      dep.custDeptNumber = "";
      this.setState({dep: dep})
    }
  }
  onCancel = () => {
    let {fKey,dep} = this.state;
    fKey++;
    dep.companyName = undefined;
    dep.companyOID = undefined;
    this.setState({
      fKey,
      dep,
    })
    this.props.form.resetFields();
    this.props.close(false);
  }
  handleSubmit = (e) => {
    let dep = this.state.dep;
    e.preventDefault();
    if(dep.isEnableDepCompany === "OPEN" && !dep.companyOID){
      message.warn("开启了部门关联公司，公司必填");
      return;
    }
    if (this.state.c_type === "C_CHILD") {
      this.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          values.parentDepartmentOID = this.state.dep.parentDepartmentOID;
          values.parentId = this.state.dep.parentId;
          values.i18n = dep.i18n;
          values.name = dep.name;
          values.companyOID = dep.companyOID;
          this.createChildDep(values, this.state.dep.treeNode);
        }
      })
    } else if (this.state.c_type === "C_DEP") {
      this.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          values.parentDepartmentOID = this.state.dep.parentDepartmentOID;
          values.parentId = this.state.dep.parentId;
          values.i18n = dep.i18n;
          values.name = dep.name;
          values.companyOID = dep.companyOID;
          this.createTopDep(values, this.state.dep.treeNode);
        }
      })
    }
  }
  handleFormChange = () => {
    this.setState({
      loading: false,
    })
  }
  //创建子部门
  //treeNode当前部门树节点
  createChildDep = (data, treeNode) => {
    this.setState({
      loading: true
    })
    let {dep} = this.state;
    OrgService.createChildDep(data, treeNode)
      .then((res) => {
        dep.name = "";
        dep.custDeptNumber = "";
        this.onCancel();
        this.setState({
          dep,
          loading: false
        })
      })
      .catch(() => {
        this.setState({
          loading: false
        })
      })
  }
  //创建顶层部门,或者平级部门
  //treeNode当前部门树节点
  createTopDep = (data, treeNode) => {
    this.setState({
      loading: true
    })
    let {dep} = this.state;
    OrgService.createTopDep(data, treeNode)
      .then((res) => {
        dep.name = "";
        dep.custDeptNumber = "";
        this.onCancel();
        this.setState({
          dep,
          loading: false
        })
      })
      .catch(() => {
        this.setState({
          loading: false
        })
      })
  }

  i18nChange = (name, i18nName) => {
    let {dep} = this.state;
    dep.name = name;
    dep.i18n = {
      name: i18nName
    };
    this.setState({
      dep,
    })
  }
  custDeptNumberChange=(e)=>{
    let {dep} = this.state;
    dep.custDeptNumber = trim(e.target.value);
    this.setState({
      dep,
    })
  }
  handleCompanyCodeChange = (e) => {
    let {dep} = this.state;
    if (e.length > 0) {
      dep.companyOID = e[0].companyOID;
      dep.companyName = e[0].name;
    } else {
      dep.companyOID = "";
      dep.companyName = "";
    }
    this.setState({
      dep
    })
  }
  render() {
    const {getFieldDecorator} = this.props.form;
    const {loading, dep} = this.state;
    const formItemLayout = {
      labelCol: { span: 6, offset: 1 },
      wrapperCol: { span: 14, offset: 1 }
    };
    return (
      <div className="org-new-dep">
        <Form onSubmit={this.handleSubmit} onChange={this.handleFormChange}>
          {/*所属部门*/}
          <FormItem {...formItemLayout}
                    label={messages('enterprise-manage.key118'/*所属部门*/)}
          >
            {getFieldDecorator('parentName', {
              initialValue: dep.parentName,
              rules: [],
            })(
              <Input disabled={true} placeholder={messages('common.please.enter')}/>
            )}
          </FormItem>


          <FormItem {...formItemLayout}
                    label={<span>
                      <span className='required-red'>*&nbsp;</span>
                      <span>{messages('enterprise-manage.key119'/*部门名称*/)}</span>
                    </span>}
          >
            {getFieldDecorator('name', {
              initialValue: dep.name,
            })(
              <div>
                <LanguageInput
                  key={this.state.fKey}
                  name={dep.name}
                  i18nName={dep.i18n.name}
                  isEdit={false}
                  nameChange={this.i18nChange}
                />
              </div>
            )}
          </FormItem>

          {/*部门编码*/}
          <FormItem {...formItemLayout}
                    label={messages('enterprise-manage.key120'/*部门编码*/)}
          >
            {getFieldDecorator('custDeptNumber', {
              initialValue: dep.custDeptNumber
            })(
                <Input key={this.state.fKey}
                       onChange={this.custDeptNumberChange}
                       placeholder={messages('common.please.enter')}/>
            )}
          </FormItem>
          {/*关联公司 开启状态：有默认值，是上级部门的公司*/}
          {/*关联公司 关闭状态：无默认值*/}
          <FormItem {...formItemLayout}
                    label={
                      <span>
                        {dep.isEnableDepCompany === "OPEN" && <span className="required-red">*&nbsp;</span>}
                           <span>{messages('enterprise-manage.key352')/*所属公司*/}</span>
                        </span>
                    }
          >
            <div>
              <Chooser single={true}
                       type="department_connect_company"
                       value={dep.companyOID ? [
                         {
                           name: dep.companyName,
                           companyOID: dep.companyOID,
                         }
                       ] : []}
                       placeholder={messages("common.please.select")}
                       labelKey="name"
                       valueKey="companyOID"
                       onChange={this.handleCompanyCodeChange}
                       // listExtraParams={{parentDepartmentId: dep.parentId}}
              />
              {/*传父级部门id过滤公司 后端规则逻辑：*/}
              {/*可选公司范围 = (所有公司 - 已经选择的公司 + 父级部门所在公司)*/}
            </div>
          </FormItem>
          <div className="slide-footer">
            <Button type="primary" htmlType="submit" loading={loading}>{messages('common.save')}</Button>
            <Button onClick={this.onCancel}>{messages('common.cancel')}</Button>
          </div>
        </Form>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    organization: state.budget.organization,
    company: state.login.company,
    language: state.main.language,
    tenantMode: state.main.tenantMode
  }
}

const WrappedOrgNewDep = Form.create()(OrgNewDep);
export default connect(mapStateToProps)(WrappedOrgNewDep);

